package net.asfun.jvalog.control;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.google.appengine.api.datastore.Blob;

import net.asfun.jvalog.common.InteractException;
import net.asfun.jvalog.entity.File;
import net.asfun.jvalog.mvc.RequestMapping;
import net.asfun.jvalog.service.MediaService;
import net.asfun.jvalog.util.RequestUtil;
import net.asfun.jvalog.util.ResponseUtil;
import net.asfun.jvalog.vo.Pager;

public class MediaController {
	
	@RequestMapping("/media")
	public String index(HttpServletRequest req, Map<String, Object> model) {
		int page = RequestUtil.getIntParam(req, "page");
		Pager pager = new Pager(page);
		model.put("medias", MediaService.listAll(pager));
		model.put("pager", pager);
		return "medias.html";
	}
	
	@RequestMapping("/media/create")
	public String create(HttpServletRequest req, Map<String, Object> model) {
		return "media.html";
	}
	
	@RequestMapping("/media/upload")
	public String upload(HttpServletRequest req, Map<String, Object> model) {
		File file = new File();
		file.setDate(new Date());
		if ( ServletFileUpload.isMultipartContent(req) ) {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setSizeMax(1024*1024*2);
			try {
				FileItemIterator it = upload.getItemIterator(req);
				while (it.hasNext()) {
					FileItemStream item = it.next();
					InputStream input = item.openStream();
					if ( item.isFormField() ) {
						if ( "name".equals(item.getFieldName()) ) {
							String fileName = Streams.asString(input);
							if ( fileName != null && fileName.trim().length() > 0 ) {
								file.setName(fileName);
							}
						}
						continue;
					}
					file.setMime(item.getContentType());
					if ( file.getName() == null ) {
						file.setName(item.getName());
					}
					file.setType(0);//TODO BY MIME
					int len = 0,le =0;
					byte[] by2 = new byte[1024]; //1KB
					byte[] bytesum = new byte[1024*1024]; //1MB
					while ((le = input.read(by2)) != -1) {
						System.arraycopy(by2, 0, bytesum, len, le);
						len += le;
					}
					input.close();
					byte[] byt = Arrays.copyOf(bytesum, len);
					file.setBytes(new Blob(byt));
				}
			} catch (Exception e) {
				throw new InteractException("uploading file error.");
			}
			MediaService.add(file);
		} else {
			throw new InteractException("Please upload a file.");
		}
		return ResponseUtil.feedback("media.upload", req, model);
	}
	
	@RequestMapping("/media/delete")
	public String delete(HttpServletRequest req, Map<String, Object> model) {
		Long[] ids = RequestUtil.getLongParams(req, "id");
		for(int i=0; i<ids.length; i++) {
			MediaService.delete(ids[i]);
		}
		return ResponseUtil.feedback("media.delete", req, model);
	}
	
	@RequestMapping("/media/rename")
	public String update(HttpServletRequest req, Map<String, Object> model) {
		Long id = RequestUtil.getLongParam(req, "id");
		String name = RequestUtil.getRequiredParam(req, "name");
		MediaService.rename(id, name);
		return ResponseUtil.feedback("media.rename", req, model);
	}
}
